package com.wise.site.main;


import com.wise.site.R;
import com.wise.site.WiseSiteApplication;
import com.wise.site.more.MorePush;
import com.wise.site.protocol.result.ModelResult;
import com.wise.site.push.PushService;
import com.wise.site.utils.CommentUtils;
import com.wise.site.utils.Constanct;
import com.wise.site.utils.DataCache;

import android.R.integer;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View.OnClickListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * loading页的展示
 * @author huangyue
 *
 * 2012-9-17
 */
public class MainIndexActivity extends ActivityGroup {
	private static final int SHOW_INDEXED = 1;
	private FrameLayout mContainer;
	private int[] mTabIds = new int[]{};
	private int mSelectedTabId = R.id.tab1;
	private ModelResult mr;
	
	private ImageView mImageView;
	private Dialog mDialog;
	
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
		public void onReceive(android.content.Context context, Intent intent) {
			String action = intent.getAction();
			if("sw.login".equals(action)){
				selectTab(R.id.tab4);
			} else if("sw.sale".equals(action)){
				Intent inten = new Intent(MainIndexActivity.this, BusinessActivity.class);
				DataCache.getInstance().put(Constanct.INFO_TYPE, 0);
				selectTab(R.id.tab2, inten);
			} else if("sw.buy".equals(action)){
				Intent inten = new Intent(MainIndexActivity.this, BusinessActivity.class);
				DataCache.getInstance().put(Constanct.INFO_TYPE, 1);
				selectTab(R.id.tab2, inten);
			} else if("sw.shop".equals(action)){
				selectTab(R.id.tab3);
			}  else if (MoreActivity.PUSH_NEW_ACTION.equals(action)){
				TextView temp = (TextView) findViewById(R.id.tab5);
				boolean isNormal = mSelectedTabId != R.id.tab5;
				int normalColor = getResources().getColor(R.color.tab_normal_text);
				int selectedColor = getResources().getColor(R.color.tab_selected_text);
				if(isNormal){
					if(PushService.HAVINGNEW){
						temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.more_icon_normal_n), null, null);
					} else {
						temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.more_normal), null, null);
					}
					
					temp.setTextColor(normalColor);
				}else{
					if(PushService.HAVINGNEW){
						temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.more_icon_selected_n), null, null);
					} else {
						temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.more_selected), null, null);
					}
					
					temp.setTextColor(selectedColor);
				}
			}
		};
	};
	
	private Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what == SHOW_INDEXED){
				initIndexer();
			}
		};
	};
	
	private DataSetObserver mModelLoaded = new DataSetObserver(){
		public void onChanged() {
			ModelResult mr = WiseSiteApplication.getContext().getModelResult();
			loadTab(mr);
		}
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_loading);
		mImageView = (ImageView) findViewById(R.id.loading_icon);
		mImageView.setImageResource(R.drawable.loading_logo);
		
		mHandler.sendEmptyMessageDelayed(SHOW_INDEXED, 2500);
		
//		mHandler.postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				mImageView.setImageDrawable(new ColorDrawable(Color.WHITE));
//				mHandler.sendEmptyMessageDelayed(SHOW_INDEXED, 500);
//			}
//		}, 500);
		
		try{
			IntentFilter filter = new IntentFilter("sw.login");
			filter.addAction("sw.sale");
			filter.addAction("sw.buy");
			filter.addAction("sw.shop");
			filter.addAction(MoreActivity.PUSH_NEW_ACTION);
			registerReceiver(mBroadcastReceiver, filter);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
    
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
    	if(event.getKeyCode() == KeyEvent.KEYCODE_BACK){
    		if(mDialog == null){
    			mDialog = showDialog(true,getString(R.string.shortcut_notify), getString(R.string.exit_review), null, 
		               getString(R.string.cancel),null, 
		               getString(R.string.sure), 
		                new DialogInterface.OnClickListener()
		                {
		                    public void onClick(DialogInterface dialog, int which)
		                    {
		                    	Runtime.getRuntime().exit(0);
		                    }
		                });
    		}
    		
    		if(!mDialog.isShowing()){
    			mDialog.show();
    		}
    	}
    	return super.dispatchKeyEvent(event);
    }
    
    /** 显示自定义弹出窗体*/
    public Dialog showDialog(boolean isCenter, String title, String msg,View contentView,
            String cancelbtnName, DialogInterface.OnClickListener cancelbtnListener,
            String okbtnName,DialogInterface.OnClickListener okbtnListener)
    {
        // 在创建新的窗体
        Builder builder = new AlertDialog.Builder(this);
        if(title != null)
        {
            builder.setTitle(title);
        }
        if(msg != null)
        {
            builder.setMessage(msg);
        }
        if(cancelbtnName != null)
        {
            builder.setNegativeButton(cancelbtnName,cancelbtnListener);
        }
        if(okbtnName != null)
        {
            builder.setPositiveButton(okbtnName, okbtnListener);
        }
        if(contentView != null)
        {
            builder.setView(contentView);
        }
                
        Dialog dialog = builder.create();
        return dialog;
    }
    
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try{
			unregisterReceiver(mBroadcastReceiver);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}

	private void initIndexer(){
		setContentView(R.layout.activity_main_index);
		ModelResult mr = WiseSiteApplication.getContext().getModelResult();
		if(mr != null){
			loadTab(mr);
		} else {
			WiseSiteApplication.getContext().setOnModelReady(MainIndexActivity.class.getName(), mModelLoaded);
		}
		mContainer = (FrameLayout) findViewById(R.id.container);
		selectTab(mSelectedTabId);
		OnClickListener tabClick = new OnClickListener() {
			public void onClick(View v) {
				selectTab(v.getId());
			}
		};
		findViewById(R.id.tab1).setOnClickListener(tabClick);
		findViewById(R.id.tab2).setOnClickListener(tabClick);
		findViewById(R.id.tab3).setOnClickListener(tabClick);
		findViewById(R.id.tab4).setOnClickListener(tabClick);
		findViewById(R.id.tab5).setOnClickListener(tabClick);
	}
	
	private void selectTab(int tabId){
		setDrawableById(mSelectedTabId, true);
		showTabContent(tabId + "", setDrawableById(tabId, false));
		mSelectedTabId = tabId;
	}
	
	private void selectTab(int tabId, Intent intent){
		setDrawableById(mSelectedTabId, true);
		setDrawableById(tabId, false);
		showTabContent(tabId + "", intent);
		mSelectedTabId = tabId;
	}

	private Intent setDrawableById(int tabId, boolean isNormal) {
		TextView temp = (TextView) findViewById(tabId);
		Intent intent = null;
		int normalColor = getResources().getColor(R.color.tab_normal_text);
		int selectedColor = getResources().getColor(R.color.tab_selected_text);
		
//		if(temp.getText() != null && temp.getTag() != null){
//			CommentUtils.getInstance().uploadCount((Integer)temp.getTag(), temp.getText().toString());
//		}
		
		switch (tabId) {
		case R.id.tab1:{
			if(isNormal){
				temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.home_normal), null, null);
				temp.setTextColor(normalColor);
			}else{
				temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.home_selected), null, null);
				temp.setTextColor(selectedColor);
			}
			intent = new Intent(this, IndexerActivity.class);
			break;
		}
		case R.id.tab2:{
			if(isNormal){
				temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.buy_normal), null, null);
				temp.setTextColor(normalColor);
			}else{
				temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.buy_selected), null, null);
				temp.setTextColor(selectedColor);
			}
			intent = new Intent(this, BusinessActivity.class);
			break;
		}
		case R.id.tab3:{
			if(isNormal){
				temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.shop_normal), null, null);
				temp.setTextColor(normalColor);
			}else{
				temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.shop_selected), null, null);
				temp.setTextColor(selectedColor);
			}
			intent = new Intent(this, ShopActivity.class);
			break;
		}
		case R.id.tab4:{
			if(isNormal){
				temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.vip_normal), null, null);
				temp.setTextColor(normalColor);
			}else{
				temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.vip_selected), null, null);
				temp.setTextColor(selectedColor);
			}
			intent = new Intent(this, LoginActivity.class);
			break;
		}
		case R.id.tab5:{
			if(isNormal){
				if(PushService.HAVINGNEW){
					temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.more_icon_normal_n), null, null);
				} else {
					temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.more_normal), null, null);
				}
				
				temp.setTextColor(normalColor);
			}else{
				if(PushService.HAVINGNEW){
					temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.more_icon_selected_n), null, null);
				} else {
					temp.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.more_selected), null, null);
				}
				
				temp.setTextColor(selectedColor);
			}
			intent = new Intent(this, MoreActivity.class);
			break;
		}
		default:
			break;
		}
		return intent;
	}
	
	private void loadTab(ModelResult mr) {
		if(mr != null){
			if(Constanct.TAB_COUNT != mr.getTabCount()){
				Toast.makeText(this, "下载数据失败", Toast.LENGTH_LONG).show();
				return;
			}
			this.mr = mr;
			((TextView)findViewById(R.id.tab1)).setText(mr.getTabItem(1).title);
			((TextView)findViewById(R.id.tab1)).setTag(mr.getTabItem(1).id);
			((TextView)findViewById(R.id.tab2)).setText(mr.getTabItem(2).title);
			((TextView)findViewById(R.id.tab2)).setTag(mr.getTabItem(2).id);
			((TextView)findViewById(R.id.tab3)).setText(mr.getTabItem(3).title);
			((TextView)findViewById(R.id.tab3)).setTag(mr.getTabItem(3).id);
			((TextView)findViewById(R.id.tab4)).setText(mr.getTabItem(4).title);
			((TextView)findViewById(R.id.tab4)).setTag(mr.getTabItem(4).id);
			((TextView)findViewById(R.id.tab5)).setText(mr.getTabItem(5).title);
			((TextView)findViewById(R.id.tab5)).setTag(mr.getTabItem(5).id);
		}
	};
	
    private void showTabContent(String id, Intent subWindows)
    {
        if(subWindows == null) return;
        try{
	        Window localWindow = getLocalActivityManager().startActivity(id, subWindows);
	        mContainer.removeAllViews();
	        mContainer.addView(localWindow.getDecorView());
        }catch (Exception e) {
			Log.w("MainIndexActivity", null, e);
		}
    }
}
